import React, { useEffect, useState, useCallback, useMemo } from 'react';
import { observer } from 'mobx-react';
import { Table, Space, Popconfirm, Switch, Empty, Typography, Button, message } from 'antd';
import { CopyTwoTone, PlusOutlined} from '@ant-design/icons';
import { useParams } from "react-router";
import MockEdit from './MockEdit';
import MockDetail from "./MockDetail";
import mockStore from "../store/MockStore";
import apxMethodStore from "../../definition/store/ApxMethodStore";
import './mock.scss';

const { Text } = Typography;

/**
 * 接口的Mock列表页
 */
const Mock = (props) => {
    // 解构props和store
    const { tabKey } = props;
    const { findMockPage, deleteMock, updateMock, mockList } = mockStore;
    const { findServerUrl } = apxMethodStore;
    const { id } = useParams();

    // 状态管理
    const apiId = localStorage.getItem('apiId') || id;
    const workspaceId = localStorage.getItem("workspaceId");
    const [serverUrl, setServerUrl] = useState("");

    // 计算完整的mock URL
    const mockUrl = useMemo(() => {
        if (!serverUrl) return "";
        return `${serverUrl}/mockx/${workspaceId}`;
    }, [serverUrl, workspaceId]);

    /**
     * 当选项卡为mock时，获取mock列表
     */
    useEffect(() => {
        if (tabKey === "mock") {
            findMockPage(apiId);
        }
    }, [apiId, tabKey, findMockPage]);

    /**
     * 获取服务器URL
     */
    useEffect(() => {
        const getServerUrl = async () => {
            try {
                const url = await findServerUrl();
                setServerUrl(url || "");
            } catch (error) {
                console.error("获取服务器URL失败:", error);
            }
        };

        getServerUrl();
    }, [findServerUrl]);

    /**
     * 处理mock启用状态切换
     * @param {boolean} checked - 是否启用
     * @param {Object} record - 行数据
     */
    const handleEnableChange = useCallback((checked, record) => {
        const updatedRecord = {
            ...record,
            enable: checked ? 1 : 0
        };

        updateMock(updatedRecord)
            .then(() => findMockPage(apiId))
            .catch(err => {
                message.error("更新状态失败");
                console.error("更新状态失败:", err);
            });
    }, [updateMock, findMockPage, apiId]);

    /**
     * 处理删除mock
     * @param {string} mockId - Mock ID
     */
    const handleDelete = useCallback((mockId) => {
        deleteMock(mockId)
            .then(() => {
                message.success("删除成功");
                findMockPage(apiId);
            })
            .catch(err => {
                message.error("删除失败");
                console.error("删除失败:", err);
            });
    }, [deleteMock, findMockPage, apiId]);


    // 表格列配置
    const columns = useMemo(() => [
        {
            title: 'Mock名称',
            dataIndex: 'name',
            key: 'name',
            width: '25%',
            render: (text, record) => (
                <MockDetail mockId={record.id} name={text} />
            )
        },
        {
            title: '启用',
            dataIndex: 'enable',
            key: 'enable',
            width: '10%',
            render: (text, record) => (
                <Switch
                    checked={text === 1}
                    checkedChildren="启用"
                    unCheckedChildren="停用"
                    onChange={(checked) => handleEnableChange(checked, record)}
                />
            )
        },
        {
            title: '创建人',
            dataIndex: ['createUser', 'name'],
            key: 'createUser',
            width: '20%',
            render: (_, record) => (
                <div className="ws-user-item">
                    <Space>
                        <span>{record.createUser?.nickname || '未知用户'}</span>
                    </Space>
                </div>
            )
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
            width: '25%',
        },
        {
            title: '操作',
            dataIndex: 'operation',
            key: 'operation',
            width: '20%',
            render: (_, record) => (
                <Space size="middle">
                    <MockEdit
                        type="edit"
                        name="编辑"
                        {...props}
                        mockId={record.id}
                    />
                    <Popconfirm
                        title="确定删除此Mock？"
                        onConfirm={() => handleDelete(record.id)}
                        okText='确定'
                        cancelText='取消'
                    >
                        <Button
                            type="text"
                            danger
                            icon={
                                <svg className="icon-s edit-icon" aria-hidden="true">
                                    <use xlinkHref="#icon-shanchu3" />
                                </svg>
                            }
                        />
                    </Popconfirm>
                </Space>
            )
        },
    ], [props, handleEnableChange, handleDelete]);

    return (
        <div className="mock-container">
            <div className='mock-header'>
                <div className="mock-url-container">
                    <Text >MOCK地址:</Text>
                    <Text
                        className="mock-url"
                        copyable={{
                            text: mockUrl,
                            onCopy: () => message.success('已复制到剪贴板'),
                            icon: <CopyTwoTone twoToneColor={'#b7b7b7'} />
                        }}
                    >
                        {mockUrl}
                    </Text>
                </div>
            </div>
            <div className="mock-actions">
                <div className="mock-count">共 {mockList && mockList.length} 个</div>
                <MockEdit
                    btn="btn"
                    name="添加MOCK"
                    icon={<PlusOutlined />}
                    {...props}
                />
            </div>

            <div className="pi-list-box">
                <Table
                    columns={columns}
                    dataSource={mockList}
                    rowKey={record => record.id}
                    pagination={false}
                    locale={{
                        emptyText: (
                            <Empty
                                imageStyle={{ height: 80 }}
                                description={<span>暂无Mock</span>}
                            />
                        )
                    }}
                />
            </div>
        </div>
    );
};

export default observer(Mock);